//
//  HJFriendSearchController.m
//  KaiChat
//
//  Created by lx on 2023/11/7.
//

#import "HJFriendSearchController.h"
#import "HJNavigationController.h"
#import "QMUITextField.h"
#import "TJEmptyDataHandler.h"
#import "HJFriendListCell.h"
#import "HJIM.h"
#import "HJChatController.h"
#import "HJUserInfoController.h"
#import "HJSearchView.h"

@interface HJFriendSearchController ()<QMUITextFieldDelegate>

@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;
@property (nonatomic, weak) QMUITextField *textField;
@property (nonatomic, strong) NSArray *datas;


@end

@implementation HJFriendSearchController


- (void)showInController:(UIViewController *)controller {
    HJNavigationController *navController = [[HJNavigationController alloc] initWithRootViewController:self];
    [controller presentViewController:navController animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBar.lineView.hidden = YES;
    self.navigationBar.title = @"Search Friends";
    
    UIView *headerView = [UIView addToView:self.view];
    headerView.backgroundColor = UIColor.whiteColor;
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(KNavBarHight);
        make.height.offset(60);
    }];
    
    HJSearchView *searchView = [HJSearchView addToView:headerView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(10);
        make.height.offset(40);
    }];
 
    searchView.textField.maximumTextLength = 30;
    [searchView.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _textField = searchView.textField;

    _emptyDataHandler =  [TJEmptyDataHandler emptyDataHandleWithScrollView:self.tableView configuration:^TJEmptyDataType(TJEmptyDataModel * _Nonnull dataModel) {
        dataModel.iconName = @"search_empty";
        dataModel.text = @"Results not found";
        return TJEmptyDataTypeBase;
    }];
    
    self.view.backgroundColor = UIColor.whiteColor;
    self.tableViewStyle = UITableViewStylePlain;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin, 0);
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.tableView registerClass:HJFriendListCell.class forCellReuseIdentifier:@"HJFriendListCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 70;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView.mas_bottom);
        make.left.right.bottom.offset(0);
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(500 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
        [self.textField becomeFirstResponder];
    });
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidChange:(QMUITextField *)textField {
    
    NSString *keyword = textField.text;

    if (isEmptyString(keyword)) {
        for (HJChatFriendModel *obj in self.datas) {
            obj.nameAttributedstring = nil;
        }
        self.emptyDataHandler.canDisplay = NO;
        self.datas = nil;
        [self.tableView reloadData];
        return;
    }
    
    [HJIM.shareIM.userManager searchFriendByKeyword:keyword completion:^(NSArray<HJChatFriendModel *> * _Nullable datas) {
        dispatch_async_main_queue(^{
            
            for (HJChatFriendModel *obj in datas) {
                NSRange range = [obj.showName rangeOfString:keyword options:NSCaseInsensitiveSearch];
                if (range.location != NSNotFound) {
                    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:obj.showName];
                    [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.tj_mainColor range:range];
                    obj.nameAttributedstring = attrStr;
                }
            }
            self.datas = datas;
            self.emptyDataHandler.canDisplay = YES;
            [self.tableView reloadData];
        });
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJFriendListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJFriendListCell" forIndexPath:indexPath];
    HJChatFriendModel *model = self.datas[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    [self.view endEditing:YES];
    
    HJChatFriendModel *model = self.datas[indexPath.row];
    
    HJUserInfoController *infoController = [[HJUserInfoController alloc] init];
    infoController.userId = model.userId;
    [self.navigationController pushViewController:infoController];
}
 
 
- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationFullScreen;
}



@end
